<?php

namespace App\Models;

use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;

class GoodsCommon extends Model
{
    protected $table = 'yf_goods_common';
    protected $primaryKey = 'common_id';
    public $timestamps = false;
    protected $guarded = ['common_id'];
    protected $casts = [
        'goods_id' => 'array',
        'common_property' => 'array',
        'common_spec_value' => 'array',
    ];

    public static function findByIds(array $ids) : Collection
    {
        return self::whereIn('common_id', $ids)->get() ?? collect([]);
    }

    public function getGoodsId() : array
    {
        return current(current($this->goods_id));
    }

    /**
     * 按类型获取推荐商品
     *
     * 2:轮胎，3:轮毂，4:汽车用品
     * @param int $option
     * @return Collection
     */
    public static function getRecommendGoodsByOption(int $option) : Collection
    {
        return self::from('yf_goods_common as a')
            ->leftJoin('yf_goods_base as b', 'b.common_id', '=', 'a.common_id')
            ->where([
                ['a.common_state', '=', 1],
                ['a.is_del', '=', 1],
                ['a.common_verify', '=', 1],
                ['a.shop_status', '=', 3],
                ['b.goods_is_recommend', '=', 1]
            ])
            ->where(function ($query) use ($option) {
                switch ($option) {
                    case 4:
                        return $query->whereNotIn('a.cat_id', [30, 31]);
                    case 3:
                        return $query->where('a.cat_id', 31);
                    case 2:
                    default:
                        return $query->where('a.cat_id', 30);
                }
            })
            ->limit(10)
            ->get();
    }

    public static function getActivityGoods(CarActivity $carActivity, array $params = []) : LengthAwarePaginator
    {
        $cat_ids = $carActivity->goodsCat->getAllChildrenIds();
        array_push($cat_ids, $carActivity->car_cat_id);

        return self::from('yf_goods_common as a')
            ->leftJoin('yf_shop_base as b', 'b.shop_id', '=', 'a.shop_id')
            ->leftJoin('yf_transport_area as c', 'c.shop_id', '=', 'a.shop_id')
            ->leftJoin('yf_base_district as d', 'd.district_id', '=', 'b.district_id')
            ->leftJoin('yf_base_district as f', 'f.district_id', '=', 'd.district_parent_id')
            ->leftJoin('yf_goods_base as g', 'g.common_id', '=', 'a.common_id')
            ->select(
                'a.*', 'b.shop_address', 'b.shop_name', 'b.shop_self_support', 'b.district_id',
                'd.district_parent_id', 'f.district_name', 'g.goods_id as gid', 'a.common_price as g_price'
            )
            ->addSelect(\DB::raw('2 as g_m'))
            ->distinct()
            ->where([
                ['a.is_del', '=', 1],
                ['a.common_state', '=', 1],
                ['a.common_verify', '=', 1],
                ['a.common_stock', '>', 0]
            ])
            ->whereIn('a.cat_id', $cat_ids)
            // 排除推荐的商品
            ->whereNotIn('a.common_id', $carActivity->goods_common_id ?? [])
            // 品牌
            ->when(array_get($params, 'brand_id'), function ($query) use ($params) {
                return $query->where('a.brand_id', $params['brand_id']);
            })
            // 最低价格
            ->when(array_get($params, 'min_price'), function ($query) use ($params) {
                return $query->where('a.common_price', '>=', $params['s_price_min']);
            })
            // 最高价格
            ->when(array_get($params, 'max_price'), function ($query) use ($params) {
                return $query->where('a.common_price', '<=', $params['max_price']);
            })
            // 商品名称
            ->when(array_get($params, 'common_name'), function ($query) use ($params) {
                return $query->where('a.common_name', 'like', "%$params[common_name]%");
            })
            // 车型
            ->when(array_get($params, 'property_id')  && array_get($params, 'car_type_id'), function ($query) use ($params) {
                $catType = CarType::find($params['car_type_id']);
                // 轮胎规格
                $spec_info = [];
                if ($params['property_id'] == 47) {
                    $spec_info = [$catType->front_tire_specification, $catType->rear_tire_specification];
                }
                // 轮毂规格
                if ($params['property_id'] == 60) {
                    $spec_info = [$catType->front_tire, $catType->rear_tire];
                }
                $carPropertyValueIds = CarPropertyValue::whereIn('car_property_value', $spec_info)
                    ->pluck('car_property_value_id')
                    ->toArray();

                return $query->whereIn('a.spec_info', $carPropertyValueIds);
            })
            // 商品对应属性
            ->when(array_get($params, 'property_value_ids'), function ($query) use ($params) {
                $intersectCommonIds = CarPropertyIndex::getIntersectCommonIdByPropertyValueId($params['property_value_ids']);

                return $query->whereIn('a.common_id', $intersectCommonIds);
            })
            // 排序
            ->when(array_get($params, 'order'), function ($query) use ($params) {
                switch ($params['order']) {
                    // 价格从高到低
                    case 'common_price_desc':
                        return $query->orderBy('a.common_price', 'DESC');
                    // 价格从低到高
                    case 'common_price_asc':
                        return $query->orderBy('a.common_price', 'ASC');
                    // 7天上新
                    case 'common_sell_time':
                        return $query->orderBy('a.common_add_time', 'DESC');
                    // 好评优选
                    case 'goods_evaluation':
                        return $query->leftJoin('yf_goods_evaluation as e', 'e.common_id', '=', 'a.common_id')
                            ->orderBy('e.scores', 'DESC');
                    // 自营优先
                    case 'shop_self_support':
                        return $query->orderBy('a.shop_self_support', 'DESC');
                    // 销量排序
                    case 'common_salenum':
                    default:
                        return $query->orderBy('a.common_salenum', 'DESC');
                }
            }, function ($query) {
                $sortField = 'a.common_displayorder';
                $order = 'ASC';
                if ($field = WebConfig::value('order_by')) {
                    $sortField = 'a.' . $field;
                    $order = 'DESC';
                }

                return $query->orderBy($sortField, $order);
            })
            ->paginate(10);

        // TODO: 判断商品是否有团购活动 如果团购价格小于商品价格 将 g_price 改为团购价格，将 g_m 改为 1
    }
}
